import { Avatar, Button, Col, message, Row, Upload } from 'antd';
import React, { useState } from 'react';
import { PersonalCenterAPI } from '../common/type';
import { UploadOutlined } from '@ant-design/icons';
import { getTenant } from '@/utils';
import { getBaseUrl } from '@/services/urlconst';
import { CropperModal } from './CropperModal';
// import Cropper from 'react-cropper';
// import "cropperjs/dist/cropper.css"; // 引入Cropper对应的css

import imgSrcUser from '../../../../../../../public/image/userAvatar.png';

const baseUrl = getBaseUrl();
export const CenterAvatar = React.forwardRef<
  PersonalCenterAPI.ICenterAvatarRef,
  PersonalCenterAPI.ICenterAvatarView
>(({ userInfoObj, reloadDetailInfo }, ref) => {
  const prefixCls = 'centerview-';
  // const cropperRef = useRef<any>(null); //右侧表单ref

  /**
   * 是否展示上传
   */
  const [isShowUpPic, setIsShowUpPic] = useState<boolean>(false);

  const [cropperSrc, setCropperSrc] = useState<any>('');

  const [fileImageInfo, setFileImageInfo] = useState<any>({
    selectedImageFile: [],
    fileName: '',
    isShowUpPic: false,
    editImageShow: false,
  });

  /**
   * 类型限制
   * @param file 文件对象
   * @returns
   */
  const isTypeCorrect = (file: any) => {
    let name = file.name;
    let arr = name.split('.');
    if (arr.includes('jpg') || arr.includes('png')) {
      return true;
    } else {
      return false;
    }
  };

  /**
   *
   * @param file
   */
  const showPic = (file: any) => {
    const fileReader = new FileReader();
    fileReader.onload = (e: any) => {
      const dataURL = e.target.result;
      // this.setState({ src: dataURL })
      setCropperSrc(dataURL);
    };

    fileReader.readAsDataURL(file);
  };

  /**
   * 上传配置
   */
  const uploadProps = {
    name: 'uploadImage',
    accept: '.png,.jpg',
    showUploadList: false,
    action: baseUrl + '/commonController/uploadImage',
    headers: {
      tenantName: getTenant(),
    },
    onRemove: (file: any) => {
      let fileObj: any = {
        ...fileImageInfo,
        selectedImageFile: [],
        isShowUpPic: true,
        editImageShow: false,
      };
      setFileImageInfo(fileObj);
    },
    beforeUpload: (file: any) => {
      let typeCorrect = isTypeCorrect(file);
      if (typeCorrect) {
        let fileObj: any = {
          ...fileImageInfo,
          selectedImageFile: [file],
          fileName: file.name,
          isShowUpPic: false,
          editImageShow: true,
        };
        setFileImageInfo(fileObj);
        showPic(file);
      } else {
        message.error('上传格式错误，请上传(.png , .jpg)的文件格式');
      }
      return false;
    },
    selectedImageFile: fileImageInfo?.selectedImageFile,
  };

  /**
   * 上传成功
   */
  const uploadReload = () => {
    setIsShowUpPic(false);
    let fileObj: any = {
      ...fileImageInfo,
      editImageShow: false,
    };
    setFileImageInfo(fileObj);
    reloadDetailInfo();
  };

  return (
    <>
      {/* <div className={prefixCls + 'avatarTitle'}>
        <TypographyTitle
          level={5}
          style={{
            margin: '0px 0px 1rem',
          }}
        >
          更换头像
        </TypographyTitle>
      </div> */}
      <Row className={prefixCls + 'avatarRow'}>
        <Col span={24}>
          <div
            onMouseEnter={(e) => {
              e.stopPropagation();
              setIsShowUpPic(true);
            }}
            style={{ height: 200, width: 200 }}
          >
            <Avatar size={200} src={userInfoObj?.imageUrl || imgSrcUser} />
          </div>
          {isShowUpPic ? (
            <div className={prefixCls + 'avatarRow-picUpload'}>
              <Upload {...uploadProps}>
                <Button
                  style={{
                    width: 200,
                    height: 200,
                    borderRadius: 200,
                    background: 'rgba(0,0,0,0.4)',
                  }}
                >
                  <UploadOutlined style={{ color: '#fff', fontSize: 28 }} />
                </Button>
              </Upload>
            </div>
          ) : null}
        </Col>
        <div style={{ marginTop: 20, textAlign: 'center', width: 200 }}>
          {isShowUpPic && (
            <Button
              onClick={() => {
                setIsShowUpPic(false);
                let fileObj: any = {
                  ...fileImageInfo,
                  editImageShow: false,
                };
                setFileImageInfo(fileObj);
              }}
            >
              取消上传
            </Button>
          )}
        </div>
      </Row>

      {fileImageInfo?.editImageShow && (
        <CropperModal
          onClose={() => {
            let fileObj: any = {
              ...fileImageInfo,
              editImageShow: false,
            };
            setFileImageInfo(fileObj);
          }}
          visible={fileImageInfo?.editImageShow}
          cropperSrc={cropperSrc}
          fileName={fileImageInfo.fileName}
          selectedImageFile={fileImageInfo.selectedImageFile}
          userInfoObj={userInfoObj}
          uploadReload={uploadReload}
        />
      )}
    </>
  );
});
